package com.zkingsoft.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zkingsoft.command.Command;
import com.zkingsoft.command.CommandFactory;

import com.zkingsoft.util.DBUtil;

/**
 * 前端控制器---负责接收所有的请求(业务请求)
 * @author shushine
 *
 */
public class FrontController extends HttpServlet {

	private static final long serialVersionUID = 2718582163398717315L;
	
	public Map<String,String> commandMap = new HashMap<String,String>();
	
	//获取Command工厂对象
	private CommandFactory factory = null;
	
	public void init() {
		DBUtil.initProeprties(this.getServletContext().getRealPath("/WEB-INF/jdbc.properties"));
		DBUtil.getConnection();	
		factory = CommandFactory.newInstance();
	}	
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
		int beginIndex = uri.lastIndexOf("/");
		uri = uri.substring(beginIndex);
		int endIndex = uri.indexOf(".");
		String prefix = uri.substring(1, endIndex);//获取请求资源的前缀名
		Command command = null;
		//从工程中获得Command实例对象
		command = factory.getCommand(prefix);
		try {
			command.execute(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
}
